<script setup>
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import router from "../router/index.js";
import { ref, reactive } from "vue";
import { RouterView } from "vue-router";
import request from "../utils/request.js";
import { useUserStore } from "../stores/user.js";
import { ElMessage } from "element-plus";

// 分页功能，模糊查询
const current = ref(1);
const size = ref(8);
const total = ref(0);
// 搜索框的双向绑定值，用于模糊查询，默认为空
const name = ref("");

const data = reactive({
  // table表格展示的数据
  booklistData: [],
});

const show = () => {
  request
    .get("/book/selectBookByPage", {
      params: {
        name: name.value,
        current: current.value,
        size: size.value,
      },
    })
    .then((res) => {
      // res不为空展示数据，为空证明未登录或者过期
      if (res) {
        // 将分页查询到的数据存入数组中
        // console.log(res);
        data.booklistData = res.data.records;
        total.value = res.data.total;
      }
    });
};
show();

// 重置
const reset = () => {
  current.value = 1;
  name.value = "";
  show();
};

// 分页查询相关函数
const next_click = (row) => {
  current.value = row;
  // console.log();
  show();
};

const prev_click = (row) => {
  current.value = row;
  show();
};

const handleCurrentChange = (row) => {
  current.value = row;
  show();
};

// 查看详情页
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const bookxq = reactive({});

const showXq = (book) => {
  dialogFormVisible.value = true;
  bookxq.value = book;
  // 点击详情时顺便像后端发送请求获取该书的评价，存储起来
  request.get("/comment/selectCommentById/" + book.id).then((res) => {
    if (res.code === "200") {
      coData.commentData = res.data;
      // console.log(coData.commentData);
    }
  });
};

// 买书
const userId = ref();
userId.value = useUserStore().getUser.id;

const buyBook = (book) => {
  console.log(book.id);
  request
    .get("/book/buyBookById", {
      params: {
        bookId: book.id,
        userId: userId.value,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        ElMessage.success(res.msg);
      } else {
        ElMessage.error(res.msg);
      }
    });
};

// 书籍的评价在右侧展示.数据在点击详情页面的时候像后端获取
const rightComment = ref(false);
const coData = reactive({
  commentData: [],
});

const showComment = () => {
  rightComment.value = true;
};

const dialogVisible = ref(false);
const pinglun = ref("");
const addComment = (bookId) => {
  request
    .get("/comment/addComment", {
      params: {
        userId: userId.value,
        bookId: bookId,
        content: pinglun.value,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        ElMessage.success(res.msg);
        
      }
    });
};

const centerDialogVisible = ref(false);

const showBorrow = () => {
  // 借书之前先查看积分，积分不足不可借书
  request.get("/infor/selectPoints/" + userId.value).then((res) => {
    if (res.code === "200") {
      centerDialogVisible.value = true;
    } else if (res.code === "300") {
      ElMessage.error(res.msg);
    }
  });
};

const value4 = ref("");
const confirmBrrow = (book) => {
  // 转化成日期格式，再调用toLocaleDateString函数（把date对象的日期部分转换成字符串，后台用Date类型接受即可）
  const beginDate = new Date().toLocaleDateString();
  const endDate = new Date(Date.parse(value4.value)).toLocaleDateString();
  // console.log(beginDate);
  // 报400错误，是因为传递的参数名称和后台接收的参数名称不一致，一定要一样！！！！！，不是日期格式的问题！！！！！
  request
    .get("/borrow/addBorrow", {
      params: {
        beginDate: beginDate,
        endDate: endDate,
        userId: userId.value,
        bookId: book.id,
        bookName: book.bookName,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        ElMessage.success(res.msg);
        centerDialogVisible.value = false;
      }
    });
};

</script>

<template>
  <div class="booklist">
    <div class="r_top">
      <div class="r_top_l">
        <el-input
          v-model="name"
          placeholder="请输入"
          style="width: 500px; border: 1px solid orange; margin-right: 5px"
        />
        <el-icon :size="25" style="vertical-align: middle" @click="show()"
          ><Search
        /></el-icon>
        <!-- 重置 -->
        <el-button type="primary" @click="reset" style="margin-left: 60px">
          <el-icon><RefreshLeft /></el-icon>
          <span>重置</span>
        </el-button>

      </div>
    </div>
    <div class="r_main">
      <!-- 通过v-for，弹性盒布局循环展示书籍 -->
      <div class="r_books">
        <div class="r_b" v-for="book in data.booklistData" :key="book">
          <div class="r_img">
            <!-- 这个时候不用value.什么什么，因为booklistData是在data里面 -->
            <img :src="book.photo" alt="" />
          </div>
          <div class="r_jianjie">
            <div>
              书名：
              <span style="font-weight: 900">{{ book.bookName }}</span>
            </div>
            <div>
              作者：
              <span style="font-weight: 900">{{ book.writer }}</span>
            </div>
          </div>
          <div class="r_option">
            <el-button type="primary" @click="showXq(book)">
              查看详情
            </el-button>
            <!-- <el-button type="primary" @click="addShopCar(book)">加入购物车</el-button> -->
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <div class="r_page">
        <el-pagination
          small
          background
          :pager-count="8"
          layout="prev, pager, next"
          :total="total"
          :page-size="size"
          @current-change="handleCurrentChange"
          class="mt-4"
          @next-click="next_click"
          @prev-click="prev_click"
        />
      </div>
      <!-- 详情页面的对话框 -->
      <el-dialog v-model="dialogFormVisible" title="Shipping address">
        <el-form :model="bookxq">
          <el-form-item label="封面" :label-width="formLabelWidth">
            <!-- 这个时候就需要value，因为是单独const定义的 -->
            <img
              :src="bookxq.value.photo"
              alt=""
              style="width: 200px; height: 150px; margin-left: 50px"
            />
          </el-form-item>
          <el-form-item label="书名" :label-width="formLabelWidth">
            <el-input v-model="bookxq.value.bookName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="作者" :label-width="formLabelWidth">
            <el-input v-model="bookxq.value.writer" autocomplete="off" />
          </el-form-item>
          <el-form-item label="简介" :label-width="formLabelWidth">
            <el-input v-model="bookxq.value.detail" autocomplete="off" />
          </el-form-item>
          <el-form-item label="价格" :label-width="formLabelWidth">
            <el-input v-model="bookxq.value.bookPrice" autocomplete="off" />
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-button text @click="showComment()" style="color: blue"
              >该书的相关评价</el-button
            >
            <!-- 写评论 -->
            <div>
              <el-button text @click="dialogVisible = true">
                我也去评论
              </el-button>

              <el-dialog
                v-model="dialogVisible"
                title="发表评论"
                width="30%"
                draggable
              >
                <el-input v-model="pinglun"></el-input>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button
                      type="primary"
                      @click="addComment(bookxq.value.id)"
                    >
                      提交
                    </el-button>
                  </span>
                </template>
              </el-dialog>
            </div>

            <el-drawer
              v-model="rightComment"
              title="用户评论"
              direction="rtl"
              size="35%"
            >
              <el-table :data="coData.commentData" height="600px">
                <el-table-column property="userId" label="用户ID" width="120" />
                <el-table-column property="content" label="评论" width="250" />
                <el-table-column property="time" label="时间" />
              </el-table>
            </el-drawer>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="r_dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="buyBook(bookxq.value)">
              购买
            </el-button>
            <el-button @click="showBorrow" type="primary"> 借阅 </el-button>

            <el-dialog
              v-model="centerDialogVisible"
              title="借阅"
              width="30%"
              align-center
            >
              <el-date-picker
                v-model="value4"
                type="dates"
                placeholder="Pick one or more dates"
              />
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="centerDialogVisible = false"
                    >取消</el-button
                  >
                  <el-button type="primary" @click="confirmBrrow(bookxq.value)">
                    提交
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.booklist {
  min-width: 1000px;
}
.r_top {
  /* 设置最小宽度，防止窗口缩小后，界面乱套 */
  display: flex;
  min-width: 800px;
  height: 60px;
  line-height: 60px;
  border-bottom: 1px solid #ccc;
  background-color: aliceblue;
}
.r_top_l {
  box-sizing: border-box;
  flex: 1;
  min-width: 800px;
  color: dodgerblue;
  font-weight: bold;
  padding-left: 80px;
}
.r_top_r {
  min-width: 200px;
  text-align: right;
  padding-right: 10px;

  padding-right: 40px;
}

.r_books {
  min-width: 800px;
  min-height: 550px;
  display: flex;
  /* 换行 */
  flex-wrap: wrap;
  /* 子元素环绕 */
  justify-content: space-around;
  padding: 10px;
  margin-bottom: 5px;
}
.r_books .r_b {
  width: 250px;
  height: 250px;
  margin: 10px;
  background-color: burlywood;
}
.r_books .r_b img {
  width: 200px;
  height: 150px;
  margin-left: 35px;
  margin-top: 10px;
}
.r_page {
  margin-left: 20px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>